﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using TelerikStore.EbayService;
using Telerik.Web.UI;
using System.Web.Services;
using System.Xml.Linq;
using System.Xml;

namespace TelerikStore
{
    public partial class Default : System.Web.UI.Page
    {
        private static EBayData ebayContext;
        private static readonly String ebayString = "http://ebayodata.cloudapp.net";
        private static readonly string categoriesPath = "~/CategoryList.xml";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                //Get an instance of our eBay OData feed context and get the top three deals
                ebayContext = new EBayData(new Uri(ebayString));

                String dealString = "Deals";

                var items = ebayContext.Execute<Deal>(new Uri(dealString, UriKind.Relative)).ToList();

                LatestItemsRotator.DataSource = items;
                LatestItemsRotator.DataBind();
            }
        }

        protected void PerformSearch(object sender, EventArgs e)
        {
            Session.Remove("Products");
            Response.Redirect("./CategoryView.aspx?Search=" + SearchBox.Text);
        }

        protected void CategoryListView_NeedDataSource(object sender, RadListViewNeedDataSourceEventArgs e)
        {
            CategoryListView.DataSource = GetCategories(0);
        }

        public static IEnumerable<XElement> GetCategories(int startIndex)
        {
            var physPath = HttpContext.Current.Server.MapPath(categoriesPath);
            return XDocument.Load(physPath).Descendants().Where(x => x.Name.LocalName.Equals("Item"));
        }
    }
}
